package avicit.bdp.lineage.druid.analyse.handler;

import avicit.bdp.lineage.druid.analyse.SqlRequestContext;
import avicit.bdp.lineage.druid.analyse.SqlResponseContext;
import avicit.bdp.lineage.druid.anotation.SQLObjectType;
import avicit.bdp.lineage.druid.process.ProcessorRegister;
import avicit.bdp.lineage.druid.util.ClassPathScaner;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * 血缘流程处理
 *
 */
public class DefaultHandlerChain implements IHandlerChain {

    private List<IHandler> handlerList = new ArrayList<>();

    public DefaultHandlerChain() {

        ClassPathScaner scaner = new ClassPathScaner("avicit.bdp.lineage");
        try {
            List<Class> clist = scaner.findAnnotationClazz(SQLObjectType.class);
            for (Class cla : clist) {
                SQLObjectType sqlObjectType = (SQLObjectType) cla.getAnnotation(SQLObjectType.class);
                if (sqlObjectType == null) {
                    continue;
                }
                Class<?> clazz = sqlObjectType.clazz();
                ProcessorRegister.register(clazz, cla.newInstance());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public DefaultHandlerChain(List<IHandler> handlerList) {
        this.handlerList = handlerList;
    }

    @Override
    public void handle(SqlRequestContext request, SqlResponseContext response) {
        handlerList.forEach(handler -> handler.handleRequest(request, response));
    }

    public void addHandler(IHandler handler) {
        this.handlerList.add(handler);
    }

}
